import tushare as ts
import pandas as pd

# 初始化pro接口
pro = ts.pro_api('c9cdc35f82ed72ecfdd1a9d5dcb5af9bd682561911545405eae7b463')

# 获取当前日期及前9个交易日的日期
trade_date = pro.trade_cal(start_date='20230101', end_date='20231031', is_open='1')
dates = trade_date['cal_date'].tail(10).tolist()

# 拉取每日行情数据
df_list = []
for date in dates:
    df = pro.daily(trade_date=date,
                   fields=["ts_code", "trade_date", "open", "high", "low", "close", "pre_close", "change", "pct_chg",
                           "vol", "amount"])
    df_list.append(df)

# 合并数据
df_all = pd.concat(df_list)

# 输出统计表
print("数据统计表:")
print(df_all.describe())


# 定义计算技术指标的函数
def calculate_technical_indicators(df):
    df['ma5'] = df['close'].rolling(window=5).mean()  # 5日均线
    df['ma10'] = df['close'].rolling(window=10).mean()  # 10日均线

    # RSI计算
    delta = df['close'].diff()
    gain = (delta.where(delta > 0, 0)).rolling(window=14).mean()  # 上涨幅度
    loss = (-delta.where(delta < 0, 0)).rolling(window=14).mean()  # 下跌幅度
    rs = gain / loss
    df['rsi'] = 100 - (100 / (1 + rs))

    return df


# 对每只股票计算技术指标
df_processed = df_all.groupby('ts_code').apply(calculate_technical_indicators).reset_index(drop=True)

# 提取买点股票：5日线上穿10日线的所有股票列表
buy_signals = df_processed[
    (df_processed['ma5'] > df_processed['ma10']) & (df_processed['ma5'].shift(1) <= df_processed['ma10'].shift(1))]

# 提取买点股票列表
buy_stocks = buy_signals[['ts_code', 'trade_date', 'close', 'ma5', 'ma10']]
print("\n买点股票列表:")
print(buy_stocks)
